package com.demo1;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class MyServer1 {

	public static void main(String[] args) throws Exception {
		//1.创建服务器端对象
		ServerSocket server = new ServerSocket(9001);
		System.out.println("服务器启动中...");
		//2.等待客户端连接
		Socket socket = server.accept();
		//3.获取客户端的IP
		String ip=socket.getInetAddress().getHostAddress();
		System.out.println(ip+"连接到服务器...");
		//4.获取客户单的输入流
		InputStream in = socket.getInputStream();
		//5.接收客户端发送的文件字节数组
		FileOutputStream fos = new FileOutputStream("d:\\" + ip + ".jpg");
		//6.边读边写
		byte[] buf = new byte[1024];
		int len = 0;
		while( (len=in.read(buf)) != -1 ){
			fos.write(buf, 0, len);
		}
		//7.发送到客户端提示信息
		String msg = "文件上传成功...";
		//8.获取客户端的输出流
		OutputStream out = socket.getOutputStream();
		out.write(msg.getBytes());
		fos.close();
		out.close();
		socket.close();
		server.close();
	}

}
